package wli.web.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import wli.java.file.util.*;

@WebServlet(urlPatterns = { "/left" }, initParams = {
		@WebInitParam(name = "os_type", value = "windowns"),
		//@WebInitParam(name = "os_type", value = "unix"),
		@WebInitParam(name = "unix_base_dir", value = "/usr/share/apache2/default-site"),
		@WebInitParam(name = "unix_file_host", value = "http://192.168.1.14/"),
		@WebInitParam(name = "win_base_dir", value = "C:\\Apache\\htdocs"),
		@WebInitParam(name = "win_file_host", value = "http://192.168.1.12/") })
public class LeftServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	String base_dir;
	String file_host;
	String os_type;
	String dir_sepe;

	public void init(ServletConfig config) throws ServletException {
		os_type = config.getInitParameter("os_type");
		if (os_type.equals("windowns")) {
			dir_sepe = "\\";
			base_dir = config.getInitParameter("win_base_dir");
			file_host = config.getInitParameter("win_file_host");
		}
		if (os_type.equals("unix")) {
			dir_sepe = "/";
			base_dir = config.getInitParameter("unix_base_dir");
			file_host = config.getInitParameter("unix_file_host");
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		PrintWriter out = response.getWriter();

		String base_dir_uri = "" + new File(base_dir).toURI();
		ArrayList<FileStructure> list = (ArrayList<FileStructure>) session
				.getAttribute("SIDE_BAR_LIST");
		String clicked_ufid = request.getParameter("ufid");
		String folder_open_close = request.getParameter("on");

		/**
		 * Load from the file system
		 */

		String update = request.getParameter("update");
		if (list == null || list.size() == 0 || update != null
				&& update.equals("true")) {
			File f = new File(base_dir);
			DirectoryUtil du = new DirectoryUtil(base_dir);
			du.showFiles(f.listFiles());
			list = (ArrayList<FileStructure>) du.getFileStructureList();
			//Collections.sort(list);
			session.setAttribute("SIDE_BAR_LIST", list);
			session.setAttribute("BASE_DIR", base_dir);
		}

		String category = request.getParameter("cid");
		String current_category = (String) session
				.getAttribute("CURRENT_CATEGORY");
		
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ folder_open_close);
		
		if (category != null && folder_open_close != null && folder_open_close.equals("1")) {
			if (current_category == null || !current_category.equals(category)) {
				System.out.println("AAAAAAAAAAAAAAAAAAAAAAAA: who got clicked="
						+ category);
				session.setAttribute("CURRENT_CATEGORY", category);
				clicked_ufid = getUfid(base_dir + dir_sepe + category,
						category, list);
				showAllMyChildren(base_dir + dir_sepe + category, list);
			} else {
				if (!isThisDirOpen(base_dir + dir_sepe + category, category,
						list)) {
					System.out
							.println("BBBBBBBBBBBBBBBBBBBBBB: who got clicked="
									+ category);
					session.setAttribute("CURRENT_CATEGORY", category);
					clicked_ufid = getUfid(base_dir + dir_sepe + category,
							category, list);
					showAllMyChildren(base_dir + dir_sepe + category, list);
				}
			}
		}

		if (list != null && list.size() > 0) {

			Iterator<FileStructure> it = list.iterator();
			FileStructure fstu;
			String parent_path = base_dir;
			while (it.hasNext()) {
				fstu = it.next();
				if (clicked_ufid != null && fstu.getUfid() != null
						&& fstu.getUfid().equals(clicked_ufid) && folder_open_close != null && folder_open_close.equals("1")) {
					parent_path = fstu.getPath() + dir_sepe + fstu.getName();

					if (fstu.isOpen()) {
						fstu.setIsOpen(false);
						this.hiddenAllMyChildren(parent_path, list);
					} else {
						fstu.setIsOpen(true);
						this.showAllMyChildren(parent_path, list);
					}
				} else {
					if (fstu.getUfid() == null) {
						// System.out.println("oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo"+fstu.getName());
					}
				}
			}
			session.setAttribute("SIDE_BAR_LIST", list);
		} else {
			File f = new File(base_dir);
			DirectoryUtil du = new DirectoryUtil(base_dir);
			du.showFiles(f.listFiles());
			list = (ArrayList<FileStructure>) du.getFileStructureList();
			session.setAttribute("SIDE_BAR_LIST", list);
		}

		try {
			list = (ArrayList<FileStructure>) session
					.getAttribute("SIDE_BAR_LIST");

			Iterator<FileStructure> it = list.iterator();
			FileStructure fstu;

			while (it.hasNext()) {
				fstu = it.next();
				if (fstu.getPath().equals(base_dir)) {
					fstu.setDisplyOn(true);
				}

				if (fstu.isDisplyOn()) {
					String sign = "[&spades;]";

					if (!fstu.isFile()) {
						if (fstu.hasChildren()) {
							if (fstu.isOpen()) {
								sign = "&#91;-&#93;";
							} else {
								sign = "&#91;+&#93;";
							}
						}
						out.println("<BR>" + getDirPosition(fstu.getPath())
								+ "<a href=?ufid=" + fstu.getUfid() + "&on=1>"
								+ sign + "</a>&nbsp;&nbsp;<a href=?ufid="
								+ fstu.getUfid() + ">" + fstu.getName()
								+ "</a>");
					} else {
						if (!fstu.getName().equals("index.html")
								&& !(fstu.getName().indexOf("~") > 0)) {
							out.println("<BR>"
									+ getDirPosition(fstu.getPath())
									+ "<small>&diams;</small>&nbsp;<a href="
									+ file_host
									+ fstu.getUrl().toString()
											.substring(base_dir_uri.length())
									+ " target=main_page>" + fstu.getName()
									+ "</a>");
						}
					}
				}
			}

			session.setAttribute("SIDE_BAR_LIST", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.println("<BR><BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=?update=true>[Reset]</a>");

		// out.println("</BODY>");
		// out.println("</HTML>");
	}

	private String getUfid(String dir, String name,
			ArrayList<FileStructure> list) {

		Iterator<FileStructure> it = list.iterator();
		FileStructure fstu;
		String clicked_ufid = null;
		while (it.hasNext()) {
			fstu = it.next();
			if ((fstu.getPath() + dir_sepe + fstu.getName()).equals(dir)
					&& fstu.getName().equals(name)) {
				clicked_ufid = fstu.getUfid();
				break;
			}
		}
		return clicked_ufid;
	}

	private boolean isThisDirOpen(String dir, String name,
			ArrayList<FileStructure> list) {
		boolean isopen = false;
		Iterator<FileStructure> it = list.iterator();
		FileStructure fstu;
		String clicked_ufid = null;
		while (it.hasNext()) {
			fstu = it.next();
			if ((fstu.getPath() + dir_sepe + fstu.getName()).equals(dir)
					&& fstu.getName().equals(name)) {
				if (fstu.isOpen())
					isopen = true;
				else
					isopen = false;
				break;
			}
		}
		return isopen;
	}

	private String getDirPosition(String dir) {
		StringBuffer sbf = new StringBuffer();
		for (int i = 0; i < dir.length(); i++) {

			if (os_type.equals("windowns")) {
				if (dir.charAt(i) == '\\') {
					sbf.append("&nbsp;&nbsp;&nbsp;");
				}
			}
			if (os_type.equals("unix")) {
				if (dir.charAt(i) == '/') {
					sbf.append("&nbsp;&nbsp;&nbsp;");
				}
			}
		}
		sbf.append("");

		return sbf.toString();
	}

	private void hiddenAllMyChildren(String dir, ArrayList<FileStructure> list) {
		Iterator<FileStructure> it = list.iterator();
		FileStructure fstu;
		while (it.hasNext()) {
			fstu = it.next();
			if (fstu.getPath().startsWith(dir)) {
				fstu.setDisplyOn(false);
			}
		}
	}

	private void showAllMyChildren(String dir, ArrayList<FileStructure> list) {
		System.out.println("showAllMyChildren>>>>>>" + dir);
		Iterator<FileStructure> it = list.iterator();
		FileStructure fstu;

		String path_to_show = null;
		while (it.hasNext()) {
			fstu = it.next();
			if (fstu.getPath().equals(dir)) {
				fstu.setDisplyOn(true);
				if (fstu.isOpen()) {
					fstu.setDisplyOn(true);
					path_to_show = fstu.getPath() + dir_sepe + fstu.getName();
					showAllMyChildren(path_to_show, list);
				}
			}
		}
	}
}
